package com.example.fw;

import java.util.HashSet;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactObject;


public class ContactHelper extends HelperWithWebDriverBase {

    private Contacts contactCache;
	
	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
	
	public Contacts getContacts() {
        if (contactCache == null) {
                buildContactCache();
        }
        return contactCache;
	}
	
	public Contacts getUiContacts() {
        HashSet<ContactObject> set = new HashSet<ContactObject>();              
        manager.getNavigationHelper().openMainPage();          
        List<WebElement> rows = getRowsWithDataFromTable("maintable", true);
        for (WebElement row : rows) {
        	ContactObject contact = new ContactObject()
        	.setFirstName(getFirstNameInRow(row))  
        	.setLastName(getLastNameInRow(row))                      
        	.setId(row.findElement(By.name("selected[]")).getAttribute("value"));
        	set.add(contact);
        }
        return new Contacts(set);
	}

	
	public void buildContactCache() {
        HashSet<ContactObject> set = new HashSet<ContactObject>();              
        manager.getNavigationHelper().openMainPage();          
    List<WebElement> rows = getRowsWithDataFromTable("maintable", true);
    for (WebElement row : rows) {
    	ContactObject contact = new ContactObject()
        	.setFirstName(getFirstNameInRow(row))  
        	.setLastName(getLastNameInRow(row))                      
        	.setId(row.findElement(By.tagName("input")).getAttribute("id"));
    	set.add(contact);
    }
    contactCache = new Contacts(set);
	}

	public ContactObject getContact(int index) {    
        manager.getNavigationHelper().openMainPage();	
    List<WebElement> rows = getRowsWithDataFromTable("maintable", true);
    WebElement contactRow = rows.get(index);    
    	ContactObject contact = new ContactObject()
        	.setFirstName(getFirstNameInRow(contactRow))  
        	.setLastName(getLastNameInRow(contactRow))                      
        	.setId(contactRow.findElement(By.tagName("input")).getAttribute("id"));
    	return contact;
	}
	
	public void deleteContact(int i) {
		manager.getNavigationHelper().openMainPage();
		checkContact(i);
		click(By.cssSelector("img[alt=\"Edit\"]"));
		click(By.xpath("(//input[@name='update'])[2]"));
		returnToMainPage();
		contactCache = null;

	}

	private void checkContact(int i) {
		click(By.name("selected[]"));
	}

	public void modifyContact(int i, ContactObject contactObject) {
		manager.getNavigationHelper().openMainPage();
		initContactModification(i);
		fillContactForm(contactObject, false);
		submitContactModification();
		returnToMainPage();
		contactCache = null;

	}
	
	private void initContactModification(int i) {
		checkContact(i);
		click(By.cssSelector("img[alt=\"Edit\"]"));
	}

	private void fillContactForm(ContactObject contactObject, boolean fillGroup) {
		type(By.name("firstname"), contactObject.firstName);
		type(By.name("lastname"), contactObject.lastName);
		type(By.name("address"), contactObject.address);
		type(By.name("home"), contactObject.home);
		type(By.name("mobile"), contactObject.mobilePhone);
		type(By.name("work"), contactObject.workPhone);
		type(By.name("email"), contactObject.email);
		type(By.name("byear"), contactObject.byear);
		type(By.name("address2"), contactObject.address2);
		type(By.name("phone2"), contactObject.homePhone);
		if (fillGroup) {
			select(By.name("new_group"), contactObject.selectGroup);
		} else {
			//...
		}
		select(By.name("bday"), contactObject.birthDay);
		select(By.name("bmonth"), contactObject.birthMonth);	
	}

	public void createNewContact(ContactObject contactObject) {
		manager.getNavigationHelper().goToAddNewContactCreationPage();
		fillContactForm(contactObject, true);
		submitNewContactCreation();
		returnToMainPage();
		contactCache = null;

	}

	private void returnToMainPage() {
		click(By.linkText("home page"));
	}

	private void submitNewContactCreation() {
		click(By.name("submit"));
	}
	
	private void submitContactModification() {
		click(By.name("update"));	
	}


	private String getFirstNameInRow(WebElement row) {
        return row.findElement(By.xpath(".//td[3]")).getText();
	}

	private String getLastNameInRow(WebElement row) {
        return row.findElement(By.xpath(".//td[2]")).getText();
	}

	private List<WebElement> getTableRows(String tableId) {
        return findElements(By.xpath(".//*[@id='" + tableId + "']/tbody/tr"));
	}

	protected List<WebElement> getRowsWithDataFromTable(String tableId, boolean doesLastRowNeedsToBeRemoved) {
        int rowsQuantity = getTableRows(tableId).size();
        if (doesLastRowNeedsToBeRemoved) {
                return getTableRows(tableId).subList(1, (rowsQuantity-1));
        } else {
                return getTableRows(tableId).subList(1, rowsQuantity);
        }
       
	}


}
